package com.aoxin.service.impl.course.webCourse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aoxin.mapper.SlfPriceHistoryMapper;
import com.aoxin.mapper.course.SlfSchoolCourseDtoMapper;
import com.aoxin.mapper.course.systemCourse.SchoolCoursePageDao;
import com.aoxin.mapper.course.systemCourse.SlfSyllabusMapper;
import com.aoxin.mapper.course.webCourse.MyCoursePageMapper;
import com.aoxin.mapper.course.webCourse.SlfChildrenMapper;
import com.aoxin.model.SlfPriceHistory;
import com.aoxin.model.course.SchoolCoursePage;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.course.SlfMyCoursePage;
import com.aoxin.model.dto.ChildrenCoursePackageDto;
import com.aoxin.model.dto.SchoolCourseDto;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.MyCoursePageService;
import com.aoxin.service.inter.opm.UserService;
import com.aoxin.util.EmptyUtil;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.ThreadLocalUtil;

@Service
public class MyCoursePageServiceImpl implements MyCoursePageService {

	@Autowired
	private MyCoursePageMapper myCoursePageMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private SlfPriceHistoryMapper slfPriceHistoryMapper;

	@Autowired
	private SlfSchoolCourseDtoMapper slfSchoolCourseDtoMapper;

	@Autowired
	private SlfSyllabusMapper slfSyllabusMapper;

	@Autowired
	private SlfChildrenMapper slfChildrenMapper;

	@Autowired
	private SchoolCoursePageDao schoolCoursePageDao;
	
	List<Integer> listParenid=new ArrayList<Integer>();

	@Override
	@Transactional
	public Integer insertMyCoursePage(Integer courseId, Integer syllabusId, Integer childrenId)  {
		
		/**
		 * 尊享只能买两条线中的一个包
		 * 
		 * 
		 */
		
		Integer result = 0;
		if (syllabusId != null) {
			courseId = slfSyllabusMapper.getCourseId(syllabusId);
		}
		childrenId=ThreadLocalUtil.getChildren().getChildrenId();
		SlfChildren children = this.slfChildrenMapper.getAChildren(childrenId);
		Integer userId = ThreadLocalUtil.getUser().getUserId();
		Integer schoolId = ThreadLocalUtil.getChildren().getSchoolId();
		SchoolCourseDto schoolCourseDto = slfSchoolCourseDtoMapper.getSchoolCoursePage(schoolId, courseId);
		SlfMyCoursePage myCoursePage = new SlfMyCoursePage();
		myCoursePage.setChildrenId(childrenId);
		myCoursePage.setCoursePageId(courseId);
		// 判断课程包是否已近购买
		if (this.myCoursePageMapper.getMyCoursePage(myCoursePage).size() > 0) {
			throw new IllegalArgumentException(ErrorUtil.CHECK_HAS_RESULT);
		}
		// 判断余额
		SlfUser slfUser = userService.getUser(userId);
		Double lastValue=schoolCourseDto.getDiscount_price()==null?schoolCourseDto.getPrice():schoolCourseDto.getDiscount_price();
		//判断是否未尊享，并且时间没过期，且 没购买超过两个包
    	boolean isAfter = true;
    	if(children.getVipEffectiveTime()!=null){
    		DateTime now=new DateTime();
        	DateTime vipTermOfValidity=new DateTime(children.getVipEffectiveTime());
    		//vip时间不等于空  代表曾经或现在是VIP
    		List<Map<String,Object>> vipBuyPageList=myCoursePageMapper.queryVipBuyCousePage(childrenId,vipTermOfValidity.toString("yyyy-MM-dd hh:mm:ss"));
        	
        	List<SlfMyCoursePage>	listCoursePage=myCoursePageMapper.queryChildrenPageB(childrenId,vipTermOfValidity.toString("yyyy-MM-dd hh:mm:ss"));
        	List<Map<String,Object>>	listmap=myCoursePageMapper.querySlfCoursePage(courseId,schoolId);
        	
        	
        	if(now.isAfter(vipTermOfValidity)&&now.isBefore(vipTermOfValidity.plusYears(1))&&vipBuyPageList.size()==0){
        		//VIP 期间未购买包
        		//有效期内
        		isAfter=false;
        	}else if(now.isAfter(vipTermOfValidity)&&now.isBefore(vipTermOfValidity.plusYears(1))&&vipBuyPageList.size()>0&&vipBuyPageList.size()<2&&listmap.get(0).get("parent_id")!=null){
        		//VIP期间购买过包 一次包  父级不为空 校验
        		Integer parentId=Integer.parseInt(listmap.get(0).get("parent_id").toString().toLowerCase());
        		//查询关系链所有schoolPageId
        		queryAllSchoolCoursePageId(parentId);
        		// 查询VIP之前 购买的课程包是否在关系链中
        		int breakInt=0;
        		for (int i = 0,b=vipBuyPageList.size(); i <b; i++) {
        			if(listParenid.contains(Integer.parseInt(vipBuyPageList.get(i).get("school_course_page_id").toString()))){
        				breakInt++;
        			}
				}
        		if(breakInt==0){
        			isAfter=false;	
        		}
        		//更新list
        		listParenid=new ArrayList<Integer>();
        	/*	// 判断购买的课程包是否与之前购买的课程包存在 父级关系
        		List<Map<String,Object>>resultMap=myCoursePageMapper.queryData(parentId);
        		 List<Map<String,Object>>	listmaptwo=myCoursePageMapper.querySlfCoursePage(Integer.parseInt(resultMap.get(0).get("school_course_page_id").toString()) ,schoolId);
        		Integer integer= myCoursePageMapper.queryFather(Integer.parseInt(listmaptwo.get(0).get("school_course_page_id").toString()), childrenId, vipTermOfValidity.toString("yyyy-MM-dd hh:mm:ss"));
        		if(integer==0){
        			isAfter=false;	
        		}*/
        	}else if(now.isAfter(vipTermOfValidity)&&now.isBefore(vipTermOfValidity.plusYears(1))&&vipBuyPageList.size()>0&&vipBuyPageList.size()<2&&listmap.get(0).get("parent_id")==null){
        		//vip 期间购买过包但是父级为空可购买 表示能再次购买
        		isAfter=false;	
        	}
    	}
    	
		if(children.getVipLv()!=1||isAfter){
			//非尊享用户
			boolean flag1=slfUser.getLfb()<lastValue?true:false;
			if (flag1) {
				throw new IllegalArgumentException(ErrorUtil.NOT_ENOUGH_BALANCE);
			}
		}
		
		//判断是否已购买父类包
		boolean flag=this.queryUserIsBuy(childrenId, courseId);
		if(!flag){
			throw new IllegalArgumentException("请先学习完前置课程包后再购买本课程包");
		}
		
		try {
			if (!EmptyUtil.objFieldIsEmpty(schoolCourseDto, "id")) {
				SchoolCoursePage schoolCoursePage = this.schoolCoursePageDao.getSchoolCoursePageById(courseId);
				SlfMyCoursePage slfMyCoursePage = new SlfMyCoursePage();
				slfMyCoursePage.setChildrenId(childrenId);
				slfMyCoursePage.setActiveNumber(schoolCoursePage.getActiveNumber());
				slfMyCoursePage.setCoursePageId(schoolCourseDto.getId());
				slfMyCoursePage.setName(schoolCourseDto.getName());
				slfMyCoursePage.setNickName(schoolCourseDto.getNick_name());
				slfMyCoursePage.setDescription(schoolCourseDto.getDescription());
				slfMyCoursePage.setState(schoolCourseDto.getState());
				slfMyCoursePage.setUpDownState(schoolCourseDto.getUp_down_state());
				slfMyCoursePage.setParentId(schoolCourseDto.getParent_id());
				slfMyCoursePage.setSalesStartDate(schoolCourseDto.getSales_start_date());
				slfMyCoursePage.setSalesEndDate(schoolCourseDto.getSales_end_date());
				slfMyCoursePage.setEffectiveStartDate(schoolCourseDto.getEffective_start_date());
				slfMyCoursePage.setEffectiveEndDate(schoolCourseDto.getEffective_end_date());
				slfMyCoursePage.setFitAge(schoolCourseDto.getFit_age());
				slfMyCoursePage.setEndAge(schoolCourseDto.getEnd_age());
				slfMyCoursePage.setPrice(schoolCourseDto.getPrice());
					slfMyCoursePage.setType(2);
			
				slfMyCoursePage.setDiscountPrice(schoolCourseDto.getDiscount_price());
				result = myCoursePageMapper.insertMyCoursePage(slfMyCoursePage);
				if (result != 0) {
					if(children.getVipLv()!=1 ||isAfter){
						
						if ((slfMyCoursePage.getDiscountPrice()!=null &&slfUser.getLfb()>=slfMyCoursePage.getDiscountPrice())  ||
								(slfUser.getLfb() >= slfMyCoursePage.getPrice())) {
							
							SlfPriceHistory slfPriceHistory = new SlfPriceHistory();
							Double lfb;
							if(slfMyCoursePage.getDiscountPrice()!=null){
								lfb=slfUser.getLfb()-slfMyCoursePage.getDiscountPrice();
							}else{
								lfb=slfUser.getLfb() - slfMyCoursePage.getPrice();
							}
							slfUser.setLfb(lfb);
							slfUser.setUserId(userId);
							this.userService.updateUser(slfUser);
							slfPriceHistory.setUserId(userId);
							slfPriceHistory.setUserName(ThreadLocalUtil.getUser().getName());
							slfPriceHistory.setChildrenId(childrenId);
							slfPriceHistory.setChildrenName(children.getName());
							slfPriceHistory.setClassTypeId(schoolCourseDto.getType());
							slfPriceHistory.setCommodityId(schoolCourseDto.getId());
							slfPriceHistory.setCommodityName(schoolCourseDto.getName());
							slfPriceHistory.setReallyLfb(schoolCourseDto.getDiscount_price());
							slfPriceHistory.setDiscountLfb(schoolCourseDto.getDiscount_price());
							slfPriceHistory.setShouldLfb(schoolCourseDto.getPrice());
							slfPriceHistory.setState(schoolCourseDto.getState());
							slfPriceHistoryMapper.insertSlfPriceHistory(slfPriceHistory);
						}	
					}else{
						//VIP 免费购买的课程包数据
					 	List<Map<String,Object>>	listmap=myCoursePageMapper.querySlfCoursePage(courseId,schoolId);
						myCoursePageMapper.insertVipBuyCousePage(childrenId,courseId,Integer.parseInt(listmap.get(0).get("course_page_id").toString()));
						//2 为尊享购买不扣除
						result=2;
					
					}
					
					
				}
			}
		} catch (Exception e) {
			throw new IllegalArgumentException(String.format(ErrorUtil.PARAMETER_NULL, "id"));
		}
		return result;
	}

	@Override
	public List<SlfMyCoursePage> getMyCoursePage(SlfMyCoursePage slfMyCoursePage) {
		List<SlfMyCoursePage> slfMyCoursePageList = myCoursePageMapper.getMyCoursePage(slfMyCoursePage);
		return slfMyCoursePageList;
	}

	@Override
	@Transactional
	public Integer deleteMyCoursePage(Integer myCoursePageId) {
		Integer result = 0;
		if (!EmptyUtil.isEmpty(myCoursePageId)) {
			result = myCoursePageMapper.deleteMyCoursePage(myCoursePageId);
		}
		return result;
	}

	@Override
	@Transactional
	public Integer deleteMyCoursePages(List<Integer> myCoursePageIds) {
		Integer result = 0;
		if (myCoursePageIds != null && myCoursePageIds.size() > 0) {
			result = myCoursePageMapper.deleteMyCoursePages(myCoursePageIds);
		}
		return result;
	}

	@Override
	@Transactional
	public Integer updateMyCoursePage(SlfMyCoursePage slfMyCoursePage) throws IllegalAccessException {
		Integer result = 0;
		if (!EmptyUtil.objFieldsIsEmpty(slfMyCoursePage)) {
			result = myCoursePageMapper.updateMyCoursePage(slfMyCoursePage);
		}
		return result;
	}

	@Override
	public List<SlfMyCoursePage> getMyChildrenCoursePage(Integer childrenId) {
		List<SlfMyCoursePage> slfMyCoursePageList = new ArrayList<>();
		if (childrenId != null) {
			SlfMyCoursePage slfMyCoursePage = new SlfMyCoursePage();
			slfMyCoursePage.setChildrenId(childrenId);
			slfMyCoursePageList = myCoursePageMapper.getMyCoursePage(slfMyCoursePage);
		}
		return slfMyCoursePageList;
	}

	@Override
	public List<Integer> getCoursePageByUnallotted(Integer childrenId, Integer coursePackageId) {
		return this.myCoursePageMapper.getCoursePageByUnallotted(childrenId, coursePackageId);
	}

	@Override
	public List<Integer> getChildrenByCoursePage(Integer childrenId, Integer coursePackageId, Integer coursePageId) {
		return this.myCoursePageMapper.getChildrenByCoursePage(childrenId, coursePackageId, coursePageId);
	}

	@Override
	public List<ChildrenCoursePackageDto> getChildrenCoursePackage() {
		return this.myCoursePageMapper.getChildrenCoursePackage();
	}

	@Override
	public boolean queryUserIsBuy(Integer childrenId, Integer schoolCoursePageId) {
		String str=myCoursePageMapper.queryCourseIsParent(schoolCoursePageId,ThreadLocalUtil.getChildren().getSchoolId());
		//存在上级包sql返回true
		if("true".equals(str)){
			Integer integer=myCoursePageMapper.queryUserIsBuy(childrenId, schoolCoursePageId);
			//integer大于0 用户已够买上级包
			if(integer>0){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
		
	}
	@Override
	public Integer querySchoolCoursePageId(Integer coursePageId) {
		return 	myCoursePageMapper.querySchoolCoursePageId(coursePageId,ThreadLocalUtil.getChildren().getSchoolId());
	}
	
	private void queryAllSchoolCoursePageId(Integer  parentId){
	 List<Map<String,Object>>	listCoursePageData=myCoursePageMapper.queryData(parentId);
	 if(listCoursePageData.get(0).get("parent_id")!=null){
		 queryAllSchoolCoursePageId(Integer.parseInt(listCoursePageData.get(0).get("parent_id").toString()));
	 }
	 listParenid.add(Integer.parseInt(listCoursePageData.get(0).get("school_course_page_id").toString()));
	}

	
	

}
